//
//  MTFriendViewRequestVerifyCell.swift
//  MT
//
//  Created by ooops on 2020/5/6.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import Result

protocol MTFriendViewRequestVerifyCellDelegate: NSObjectProtocol {
    /// 拒绝好友请求
    func rejectInvitation()
    /// 同意好友请求
    func confrimInvitation(userName: String)
    func acceptInvitation(userName: String, eventType: Int, pushId: String?)
}

class MTFriendViewRequestVerifyCell: UITableViewCell {
    
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    var verificationInfo: JCVerificationInfo? {
        didSet {
            if let v = verificationInfo {
                JMSGUser.userInfoArray(withUsernameArray: [v.username]) { (result, error) in
                    if error == nil {
                        let users = result as! [JMSGUser]
                        let user = users.first
                        self.userIconView.mtSetImage(user?.avatar, nil)
                        self.userNickNameLabel.text = user?.displayName()
                    }
                }
                msgLabel.text = v.resaon
                getInfo(username: v.username)
                ///
                /// 入群申请人是自己 不需要显示拒绝和通过的按钮
                let isSelf: Bool = JMSGUser.myInfo().username == v.initiator
                switch v.state {
                case JCVerificationType.wait.rawValue, JCVerificationType.receive.rawValue: /// 发送方等待确认好友申请
                    rejectButton.isHidden = false
                    acceptButton.isHidden = false
                    statusLabel.isHidden = true
                    if isSelf {
                        rejectButton.isHidden = true
                        acceptButton.isHidden = true
                        statusLabel.isHidden = false
                        statusLabel.text = "等待通过审核"
                    }
                case JCVerificationType.accept.rawValue:
                    rejectButton.isHidden = true
                    acceptButton.isHidden = true
                    statusLabel.isHidden = false
                    statusLabel.text = "已通过"
                case JCVerificationType.reject.rawValue:
                    rejectButton.isHidden = true
                    acceptButton.isHidden = true
                    statusLabel.isHidden = false
                    statusLabel.text = "已拒绝"
                default:
                    break
                }
            } else {
                self.userIconView.mtSetImage("", nil)
                self.userNickNameLabel.text = ""
            }
        }
    }
    
    private func getInfo(username: String) {
        provider.rx.requestResult(.info(username)).subscribe(onNext: { [weak self] (result: Result<MineInfoResponseModel, AnyError>, isCache: Bool) in
            
            guard let weakSelf = self else {
                return
            }
            switch result {
            case let .success(response):
                
                if let code = response.code, code == 200 {
                    if let result = response.result {
                        weakSelf.model = result
                    }
                } else {
                    if let msg = response.message {
                        AlertManager.presentAlertView(message: msg)
                    }
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: globalDisposedBag)
    }
    
    var model: MineInfoModel? {
        didSet {
            guard let model = model else { return }
            /// 用户信息
            if model.age != nil && model.area != nil {
                descriptionLabel.text = "\(model.age ?? 0)岁 | \(model.area ?? "")"
            } else if model.area == nil {
                descriptionLabel.text = "\(model.age ?? 0)岁"
            } else {
                descriptionLabel.text = "\(model.area ?? "")"
            }
        }
    }
    
    weak var delegate: MTFriendViewRequestVerifyCellDelegate?
    
    lazy var userIconView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 22
        imageV.layer.borderWidth = 1
        imageV.layer.borderColor = UIColor.black.cgColor
        imageV.layer.masksToBounds = true
        return imageV
    }()
    
    lazy var userNickNameLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "帅气小伙子"
        return l
    }()
    
    lazy var descriptionLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "21岁   西湖区    8km"
        return l
    }()
    
    lazy var msgTipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        l.text = "附加留言"
        return l
    }()
    
    lazy var msgLabelBgView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        v.layer.cornerRadius = 4
        return v
    }()
    
    lazy var msgLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "f你点接收, 我点你的心"
        l.numberOfLines = 0
        l.preferredMaxLayoutWidth = ScreenWidth - 10 - 10 - 44 - 10
        l.lineBreakMode = .byWordWrapping
        return l
    }()
    
    lazy var rejectButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("拒绝", for: .normal)
        btn.addTarget(self, action: #selector(rejectRequest), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        return btn
    }()
    
    lazy var acceptButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("接受", for: .normal)
        btn.addTarget(self, action: #selector(acceptRequest), for: .touchUpInside)
        btn.setTitleColor(UIColor(hex: 0x29282b), for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        return btn
    }()
    
    lazy var statusLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(14)
        l.textColor = UIColor.text.x9b9b9b
        l.textAlignment = .center
        l.isHidden = true
        return l
    }()
    
    lazy var giftIconView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.borderColor = UIColor.black.cgColor
        imageV.layer.borderWidth = 1
        return imageV
    }()
    
    lazy var giftsLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(24)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "33"
        return l
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        return v
    }()
    
    lazy var bottomLineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        return v
    }()
    
    class func reuseIdentity() -> String {
        return "MTFriendViewRequestVerifyCellID"
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
        makeConstraint()
        self.selectionStyle = .none
    }
    
    private func setupUI() {
        contentView.addSubview(userIconView)
        contentView.addSubview(userNickNameLabel)
        contentView.addSubview(descriptionLabel)
        contentView.addSubview(msgLabelBgView)
        contentView.addSubview(msgTipLabel)
        msgLabelBgView.addSubview(msgLabel)
        contentView.addSubview(rejectButton)
        contentView.addSubview(acceptButton)
        contentView.addSubview(statusLabel)
        contentView.addSubview(bottomLineView)
        
//        contentView.addSubview(giftIconView)
//        contentView.addSubview(giftsLabel)
        
        contentView.addSubview(lineView)
    }
    
    private func makeConstraint() {
        
        userIconView.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(10)
            //make.size.equalTo(CGSize(width: 44, height: 44))
            make.width.equalTo(44)
            make.height.equalTo(44)
        }
        
        userNickNameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userIconView.snp.right).offset(10)
            make.bottom.equalTo(userIconView.snp.centerY).offset(-2)
        }
        
        descriptionLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(userIconView.snp.centerY).offset(2)
        }
        
        msgTipLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(userIconView.snp.bottom).offset(6)
        }
        
        msgLabelBgView.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(msgTipLabel.snp.bottom).offset(2)
            make.bottom.equalTo(rejectButton.snp.top).offset(-20)
            make.right.equalToSuperview().offset(-10)
        }
        
        msgLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(8)
            make.bottom.equalToSuperview().offset(-8)
            make.right.equalToSuperview().offset(-10)
        }
        
        rejectButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.bottom.equalTo(bottomLineView.snp.top)
            make.height.equalTo(36)
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        acceptButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.bottom.equalTo(bottomLineView.snp.top)
            make.height.equalTo(36)
            make.width.equalToSuperview().multipliedBy(0.5)
        }
        
        statusLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(bottomLineView.snp.top)
            make.height.equalTo(36)
            make.left.right.equalToSuperview()
        }
        
        bottomLineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(6)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(statusLabel.snp.top)
            make.height.equalTo(2)
        }
        
//        giftIconView.snp.makeConstraints { (make) in
//            make.centerY.equalTo(descriptionLabel.snp.centerY).offset(-1)
//            make.right.equalTo(giftsLabel.snp.left).offset(-10)
//            make.width.equalTo(44)
//            make.height.equalTo(44)
//        }
//
//        giftsLabel.snp.makeConstraints { (make) in
//            make.centerY.equalTo(giftIconView)
//            make.right.equalToSuperview().offset(-10)
//        }
        
    }
    
    @objc private func rejectRequest() {
        guard let info = verificationInfo else { return }
        JMSGFriendManager.rejectInvitation(withUsername: info.username, appKey: info.appkey, reason: "拒绝了你的好友请求") { (result, error) in
            if error == nil {
                info.state = JCVerificationType.reject.rawValue
                JCVerificationInfoDB.shareInstance.updateData(info)
                self.delegate?.rejectInvitation()
                self.rejectButton.isHidden = true
                self.acceptButton.isHidden = true
                self.statusLabel.isHidden = false
                self.statusLabel.text = "已拒绝"
            }
        }
    }
    
    @objc private func acceptRequest() {
        
        guard let info = verificationInfo else { return }
        JMSGFriendManager.acceptInvitation(withUsername: info.username, appKey: info.appkey) { (result, error) in
            if error == nil {
                info.state = JCVerificationType.accept.rawValue
                JCVerificationInfoDB.shareInstance.updateData(info)
                self.rejectButton.isHidden = true
                self.acceptButton.isHidden = true
                self.statusLabel.text = "已接受"
                self.statusLabel.isHidden = false
                self.delegate?.confrimInvitation(userName: info.username)
                self.delegate?.acceptInvitation(userName: info.username, eventType: 1, pushId: nil)
            }
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
